package com.mes.handler;

import com.mes.data.*;
import org.apache.commons.lang.time.DateUtils;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class ShopCalendarHandler extends BaseActionHandler {
	private Date stratDate;
	private Date endDate;
	private String[] weekday = new String[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };

	@Override
	protected JSONObject execute(Map<String, Object> parameters, String data) {
		JSONObject jsonRep = new JSONObject();
		try {
			OBContext.setAdminMode();
			final JSONObject jsonData = new JSONObject(data);
			final String[] ids = jsonData.getString("ids").split("::");
			final String[] date = jsonData.getString("dateParam").split("::");
			// 日历信息ID
			EmesShopCalendar shopCalendar = OBDal.getInstance().get(EmesShopCalendar.class, ids[0]);
			// 日历模板信息ID
			EmesCalendarTemplate template = OBDal.getInstance().get(EmesCalendarTemplate.class, ids[1]);
			// 日历模板下所有记录
			List<EmesCalendarTemplateTime> timeList = template.getEmesCalendarTemplateTimeList();
			// 该日历模板下所有有记录的
			List<EmesShopCalendarDate> dateList = shopCalendar.getEmesShopCalendarDateList();
			// 取出所有时间用于判断工作天是否可重复插入
			Map<Date, List> dateInDateMap = new HashMap<Date, List>();
			// 存储EmesShopCalendarDate，用于更新
			Map<Date, EmesShopCalendarDate> dateMap = new HashMap<Date, EmesShopCalendarDate>();
			Boolean timesFlag = dateList.isEmpty();
			if (timesFlag) {
			} else {
				for (EmesShopCalendarDate dateIndex : dateList) {
					dateInDateMap.put(dateIndex.getCalendarDate(), dateIndex.getEmesShopCalendarTimeList());
					dateMap.put(dateIndex.getCalendarDate(), dateIndex);
				}
			}
			// 处理时间
			DateMader(date);
			Calendar calendar_start = new GregorianCalendar();
			Calendar calendar_end = new GregorianCalendar();
			calendar_start.setTime(stratDate);
			calendar_end.setTime(endDate);
			// calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
			// date=calendar.getTime(); //这个时间就是日期往后推一天的结果
			// String hqlCD = "";
			// String hqlCT = "";
			EmesShopCalendarTime t = null;
			calendar_end.add(Calendar.DATE, 1);
			while (!DateUtils.isSameDay(calendar_start, calendar_end)) {
				if (dateList.isEmpty()) {
					// 如果为空，则创建当天的日历
					EmesShopCalendarDate emesShopCalendarDate = new EmesShopCalendarDate();
					emesShopCalendarDate.setCalendarDate(calendar_start.getTime());
					// 获取月份
					int month = calendar_start.get(Calendar.MONTH) + 1;
					calendar_start.add(Calendar.DATE, -1);
					// 获取一年中的第几周
					int week = calendar_start.get(Calendar.WEEK_OF_YEAR);
					calendar_start.add(Calendar.DATE, 1);
					emesShopCalendarDate.setMonth(month + "月份");
					emesShopCalendarDate.setWeekday(weekday[(calendar_start.get(Calendar.DAY_OF_WEEK) - 1)]);
					emesShopCalendarDate.setWeek("第" + week + "周");
					// 判断是否是工作日
					for (EmesCalendarTemplateTime time : timeList) {
						if (String.valueOf(calendar_start.get(Calendar.DAY_OF_WEEK) - 1).equalsIgnoreCase(time.getWeekday())) {
							if (time.getWorkEfficiency() != null) {
								emesShopCalendarDate.setWorkday(true);
							}
						}
					}
					// 存储工作日
					emesShopCalendarDate.setEmesShopCalendar(shopCalendar);
					OBDal.getInstance().save(emesShopCalendarDate);
					for (EmesCalendarTemplateTime time : timeList) {
						// 储星期几的工作时间和工作效率
						if (String.valueOf(calendar_start.get(Calendar.DAY_OF_WEEK) - 1).equalsIgnoreCase(time.getWeekday())) {
							t = new EmesShopCalendarTime();
							t.setTimeFrom(time.getTimeFrom());
							t.setTimeTo(time.getTimeTo());
							t.setWorkEfficiency(time.getWorkEfficiency());
							t.setEmesShopCalendarDate(emesShopCalendarDate);
							OBDal.getInstance().save(t);
						}
						;
					}
				} else {
					if (dateInDateMap.containsKey(calendar_start.getTime())) {
						// 如果包含已经创建的时间，则不生成当天的日历，保存原有的日历
						if (dateInDateMap.get(calendar_start.getTime()).isEmpty()) {
							// 如果为空，则创建当天的日历
							EmesShopCalendarDate emesShopCalendarDate = dateMap.get(calendar_start.getTime());
							// 判断是否是工作日
							for (EmesCalendarTemplateTime time : timeList) {
								if (String.valueOf(calendar_start.get(Calendar.DAY_OF_WEEK) - 1).equalsIgnoreCase(time.getWeekday())) {
									if (time.getWorkEfficiency() != null) {
										emesShopCalendarDate.setWorkday(true);
									}
								}
							}
							// 更新
							for (EmesCalendarTemplateTime time : timeList) {
								// 储星期几的工作时间和工作效率
								if (String.valueOf(calendar_start.get(Calendar.DAY_OF_WEEK) - 1).equalsIgnoreCase(time.getWeekday())) {
									t = new EmesShopCalendarTime();
									t.setTimeFrom(time.getTimeFrom());
									t.setTimeTo(time.getTimeTo());
									t.setWorkEfficiency(time.getWorkEfficiency());
									t.setEmesShopCalendarDate(emesShopCalendarDate);
									OBDal.getInstance().save(t);
								}
								;
							}
						}
					} else {
						// 如果为空，则创建当天的日历
						EmesShopCalendarDate emesShopCalendarDate = new EmesShopCalendarDate();
						emesShopCalendarDate.setCalendarDate(calendar_start.getTime());
						// 获取月份
						int month = calendar_start.get(Calendar.MONTH) + 1;
						calendar_start.add(Calendar.DATE, -1);
						// 获取一年中的第几周
						int week = calendar_start.get(Calendar.WEEK_OF_YEAR);
						calendar_start.add(Calendar.DATE, 1);
						emesShopCalendarDate.setMonth(month + "月份");
						emesShopCalendarDate.setWeekday(weekday[(calendar_start.get(Calendar.DAY_OF_WEEK) - 1)]);
						emesShopCalendarDate.setWeek("第" + week + "周");
						// 判断是否是工作日
						for (EmesCalendarTemplateTime time : timeList) {
							if (String.valueOf(calendar_start.get(Calendar.DAY_OF_WEEK) - 1).equalsIgnoreCase(time.getWeekday())) {
								if (time.getWorkEfficiency() != null) {
									emesShopCalendarDate.setWorkday(true);
								}
							}
						}
						// 存储工作日
						emesShopCalendarDate.setEmesShopCalendar(shopCalendar);
						OBDal.getInstance().save(emesShopCalendarDate);
						for (EmesCalendarTemplateTime time : timeList) {
							// 储星期几的工作时间和工作效率
							if (String.valueOf(calendar_start.get(Calendar.DAY_OF_WEEK) - 1).equalsIgnoreCase(time.getWeekday())) {
								t = new EmesShopCalendarTime();
								t.setTimeFrom(time.getTimeFrom());
								t.setTimeTo(time.getTimeTo());
								t.setWorkEfficiency(time.getWorkEfficiency());
								t.setEmesShopCalendarDate(emesShopCalendarDate);
								OBDal.getInstance().save(t);
							}
						}
					}
				}
				calendar_start.add(Calendar.DATE, 1);
			}
			OBDal.getInstance().commitAndClose();
			// return result;
			jsonRep.put("flag", true);
			jsonRep.put("message", "生成工厂日历成功，请重新点击该记录或点击刷新按钮查询生成的工厂日历。");
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			try {
				jsonRep.put("flag", false);
				jsonRep.put("message", "生成工厂日历失败：" + e.getMessage());
			} catch (Exception ex) {
			}
		} finally {
			OBContext.restorePreviousMode();
		}
		return jsonRep;
	}
	protected void DateMader(String[] date) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		stratDate = sdf.parse(date[0]);// 开始时间
		endDate = sdf.parse(date[1]);// 结束时间
	}
}
